import time
import uuid

from django.db import models
from django.db.models import Q

from user.models import User
from pwnote.models import PWNote


# Create your models here.
class Active(models.Model):
    GENDER_CHOICES = (
        (0, 'post'),
        (1, 'delete'),
        (2, 'put'),
        (3, 'get')
    )
    body_id = models.UUIDField(default=str(uuid.uuid4()).replace("-", ""), verbose_name="操作id")
    user_id = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户")
    pwnote_id = models.ForeignKey(PWNote, on_delete=models.CASCADE, verbose_name="联系电话")
    commands = models.SmallIntegerField()
    creat_time = models.IntegerField(default=int(time.time()), verbose_name='创建时间')
    sync_time = models.IntegerField(default=int(time.time()), verbose_name='同步时间')
    update_time = models.IntegerField(default=int(time.time()), verbose_name="更新时间")
    
    @staticmethod
    def get_active(user, start, end):
        actives = Active.objects.filter(Q(update_time__gt=start) | Q(update_time__lte=end) | Q(user_id=user)).values(
            "body_id", "commands", "creat_time", "sync_time", "update_time")
        for active in actives:
            active.sync_time = int(time.time())
            active.save()
        return list(actives)

    @staticmethod
    def get_active_hold(user, start, end):
        actives = Active.objects.filter(Q(update_time__gt=start) | Q(update_time__lte=end) | Q(user_id=user)|Q(pwnote_id__is_delete=False)).values(
            "body_id", "commands", "creat_time", "sync_time", "update_time")
        for active in actives:
            active.sync_time = int(time.time())
            active.save()
        return list(actives)
    
    class Meta:
        db_table = 'tb_active'
        verbose_name = '动作'
        verbose_name_plural = verbose_name
    
    def __str__(self):
        return self.user_id
